<template>
	<view>
		<pageHeader  @back='back' :fixed='true' :border='true'>
			<text>发布设计</text>
		</pageHeader>
		<view style="height: 16rpx;width: 750rpx;background-color: #F5F5F5;"></view>
		<view class="message title">
			<input type="text" placeholder="输入20字以内的标题" v-model="title" :maxlength='20' placeholder-style='color:#999999;font-weight:normal'/>
		</view>
		<view class="message">
			<text class="message_key">设计风格</text>
			<picker mode="selector" :range="newStyleList" @change="changeStyle" >
				<view>
					<text>{{style}}</text>
					<image src="/static/svg/pull-down.svg" mode=""></image>
				</view>
			</picker>
			<input type="text" :maxlength='6' v-if="style=='其它'" v-model="otherStyle"/>
		</view>
		<view class="message">
			<text class="message_key">户型</text>
			<picker mode="selector" :range="newLayoutList" @change="changeLayout" >
				<view  :style="{padding:layout.length>=6?'0 10rpx':''}">
					<text>{{layout}}</text>
					<image src="/static/svg/pull-down.svg" mode=""></image>
				</view>
			</picker>
			<input type="text" :maxlength='6' v-if="layout=='其它'" v-model="otherLayout"/>
		</view>
		<view class="message">
			<text class="message_key">面积</text>
			<input :maxlength='6' style="margin-left: 20rpx;width: 220rpx;" type='number' v-model="area"/>
			<text style="color: #333333;margin-left: 20rpx;">平方米</text>
		</view>
		<view class="message">
			<text class="message_key">场所</text>
			<picker mode="selector" :range="newPlaceList" @change="changePlace" >
				<view >
					<text>{{place}}</text>
					<image src="/static/svg/pull-down.svg" mode=""></image>
				</view>
			</picker>
			<input type="text" :maxlength='6' v-if="place=='其它'" v-model="otherPlace"/>
		</view>
		<view class="message addImg">
			<text class="message_key">封面图片</text>
			<image :src="imgSrc" @tap="toAddImg" v-if="imgSrc"></image>
			<image :src="imgSrc1" @tap="toAddImg" v-else></image>
		</view>
		<ImageCropper :src="url" @confirm="confirm" :crop-fixed="true" @cancel="cancel" :cropWidth='345' :cropHeight='160'></ImageCropper>
		<view class="message">
			<text class="message_key" style="color: #333333;">内容描述</text>
			<text class="example" @tap="toLookExample">内容示例</text>
		</view>
		<view class="addImgToEditor">
			<image src="/static/svg/photo.svg" mode="" @tap="addImgToEditor"></image>
		</view>
		<view class="editor_div">
			<text>{{editorNumber}}/10000</text>
			<editor id="editor" :read-only='editorReadOnly' class="ql-container" @input='editorInput'  @ready="onEditorReady" placeholder="输入描述内容…" placeholder-class='editor_placeholder'></editor>
		</view>
		<view style="height: 131rpx;"></view>
		<view class="button" :style="{borderColor:canDo?'#C84739':'#C8C8C8'}">
			<view @tap="toLook">
				<text :style="{color:canDo?'#C84739':'#C8C8C8'}">预览</text>
			</view>
			<view :style="{backgroundColor:canDo?'#C84739':'#C8C8C8'}" @tap="toAdd">
				<text>发布</text>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="popup_body">
				<view class="popup_body_body">
					<view v-for="(item,index) in chooseList" :key='index' @tap="popup_confirm" :data-value='item.content.replace("不限","其它")' :data-state='item.id'>{{item.content.replace('不限',"其它")}}</view>
				</view>
				<view class="cancel" @tap="popup_cancel">取消</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import '@/static/js/quil.js'
	import urls from "@/common/util/homeArtIndex.js"
	import ImageCropper from "@/components/invinbg-image-cropper/invinbg-image-cropper.vue"
	import pageHeader from "@/components/header/header.vue"
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	export default {
		components: {pageHeader,ImageCropper,uniPopup},
		data() {
			return {
				imgSrc1:require("@/static/svg/tianjia.svg"),
				imgSrc:"",
				url:"",
				editorCtxt:"",
				canDo:false,
				editorNumber:0,
				editorReadOnly:false,
				chooseList:[],
				choosing:"",
				style:"",
				otherStyle:"",
				layout:"",
				otherLayout:"",
				place:"",
				otherPlace:"",
				title:"",
				area:"",
				styleState:1,
				layoutState:6,
				placeState:9,
				styleList:[],
				layoutList:[],
				placeList:[],
				isEdit:false,
				id:"",
				isSuccess:false,
				isFail:false,
				examine:""
			};
		},
		onLoad(e) {
			localStorage.removeItem("releaseDesignMessage")
			if(e.isEdit){
				this.isEdit=true
				this.id=e.id
			}
			if(e.isSuccess){
				this.isSuccess=true
			}
			if(e.examine){
				this.examine=e.examine
			}
			if(e.isFail){
				this.isFail=true
			}
			this.getStyleList()
			this.getLayoutList()
			this.getPlaceList(this.isEdit)
		},
		computed:{
			newLayoutList(){
				let list=[]
				for(let a=0;a<this.layoutList.length;a++){
					list.push(this.layoutList[a].content)
				}
				return list
			},
			newStyleList(){
				let list=[]
				for(let a=0;a<this.styleList.length;a++){
					list.push(this.styleList[a].content)
				}
				return list
			},
			newPlaceList(){
				let list=[]
				for(let a=0;a<this.placeList.length;a++){
					list.push(this.placeList[a].content)
				}
				return list
			}
		},
		watch: {
			editorNumber(editorNumber) {
				this.checkCan()
				// if(editorNumber==10000){
				// 	this.editorReadOnly=true
				// }else{
				// 	this.editorReadOnly=false
				// }
			},
			otherStyle(){
				this.checkCan()
			},
			otherLayout(){
				this.checkCan()
			},
			otherPlace(){
				this.checkCan()
			},
			title(){
				this.checkCan()
			},
			area(area){
				setTimeout(()=>{
					if(area==0){
						this.area=""
					}
				},0)
				this.checkCan()
			}
		},
		methods: {
			async getStyleList(){
				let res=await urls.getKind({state:0})
				this.styleList=res.data
				for(let a=0;a<this.styleList.length;a++){
					if(this.styleList[a].content=='不限'){
						let json=this.styleList[a]
						json.content='其它'
						this.styleList.splice(a,1)
						this.styleList.push(json)
						this.style=this.styleList[0].content
						break
					}
				}
			},	
			async getLayoutList(){
				let res=await urls.getKind({state:1})
				this.layoutList=res.data
				for(let a=0;a<this.layoutList.length;a++){
					if(this.layoutList[a].content=='不限'){
						let json=this.layoutList[a]
						json.content='其它'
						this.layoutList.splice(a,1)
						this.layoutList.push(json)
						this.layout=this.layoutList[0].content
						break
					}
				}
			},	
			async getPlaceList(is){
				let res=await urls.getKind({state:2})
				this.placeList=res.data
				for(let a=0;a<this.placeList.length;a++){
					if(this.placeList[a].content=='不限'){
						let json=this.placeList[a]
						json.content='其它'
						this.placeList.splice(a,1)
						this.placeList.push(json)
						this.place=this.placeList[0].content
						break
					}
				}
				if(is){
					this.getThing()
				}
			},
			async getThing(){
				let res=await urls.editDesDraft({designId:this.id})
				let message={}
				message.title=res.data.designTitle
				message.imgSrc=res.data.coverImage
				message.styleState=Number(res.data.designStyle)
				for(let a=0;a<this.styleList.length;a++){
					if(this.styleList[a].id==message.styleState){
						message.style=this.styleList[a].content
					}
				}
				message.otherStyle=res.data.styleContent
				message.placeState=Number(res.data.designPlace)
				for(let a=0;a<this.placeList.length;a++){
					if(this.placeList[a].id==message.placeState){
						message.place=this.placeList[a].content
					}
				}
				message.otherPlace=res.data.placeContent
				message.layoutState=Number(res.data.designApartment)
				for(let a=0;a<this.layoutList.length;a++){
					if(this.layoutList[a].id==message.layoutState){
						message.layout=this.layoutList[a].content
					}
				}
				message.otherLayout=res.data.apartmentContent
				message.area=res.data.areaNumber
				message.html=JSON.parse(res.data.designContent) 
				this.examine=res.data.examine
				localStorage.setItem('releaseDesignMessage',JSON.stringify(message))
				this.getMessage()
			},
			changeLayout(e){
				this.layout=this.layoutList[e.detail.value].content
				this.layoutState=this.layoutList[e.detail.value].id
				this.checkCan()
			},
			changeStyle(e){
				this.style=this.styleList[e.detail.value].content
				this.styleState=this.styleList[e.detail.value].id
				this.checkCan()
			},
			changePlace(e){	
				this.place=this.placeList[e.detail.value].content
				this.placeState=this.placeList[e.detail.value].id
				this.checkCan()
			},
			back() {
				let isNeed=false
				if(this.title){
					isNeed=true
				}
				if(this.style!=this.styleList[0].content){
					isNeed=true
				}
				if(this.layout!=this.layoutList[0].content){
					isNeed=true
				}
				if(this.place!=this.placeList[0].content){
					isNeed=true
				}
				if(this.imgSrc){
					isNeed=true
				}
				if(this.editorNumber>0){
					isNeed=true
				}
				if(this.area){
					isNeed=true
				}
				this.editorCtxt.getContents({
					success:res=>{
						let html=res.html
						if(html&&html!='<p><br></p>'){
							isNeed=true
						}
						if(isNeed){
							uni.showModal({
								content: '是否保存草稿？',
								cancelText:'不保存',
								confirmText:'保存',
								success:res=> {
								    if (res.confirm) {
										uni.showLoading({
											mask: true
										});
										this.saveMessage()
										setTimeout(async ()=>{
											let message=JSON.parse(localStorage.getItem("releaseDesignMessage"))
											let data={}
											data.designTitle=message.title
											data.userId=localStorage.getItem("userId")
											data.coverImage=message.imgSrc
											data.designStyle=message.style=='其它'?12:message.styleState
											data.designApartment=message.layout=='其它'?12:message.layoutState
											data.designPlace=message.place=='其它'?12:message.placeState
											data.styleContent=message.style=='其它'?message.otherStyle:""
											data.apartmentContent=message.layout=='其它'?message.otherLayout:""
											data.placeContent=message.place=='其它'?message.otherPlace:""
											data.areaNumber=message.area
											data.designContent=JSON.stringify(message.html) 
											data.introduce=message.html1
											data.draft=0
											data.examine=this.examine
											let res
											if(this.isEdit&&!this.isSuccess&&!this.isFail){
												data.productId=""
												data.designId=this.id
												res=await urls.updaterotationChart(data)
											}else{
												res=await urls.addArticle(data)
											}
											uni.hideLoading()
											if(res.code==0){
												localStorage.removeItem("releaseDesignMessage")
												uni.navigateBack({
													delta: 1
												})
											}
										},20)
								    } else if (res.cancel) {
										localStorage.removeItem("releaseDesignMessage")
										uni.navigateBack({
											delta: 1
										})
								    }
								}
							})
						}else{
							uni.navigateBack({
								delta: 1
							})
						}
					}
				})
			},
			getMessage(){
                if(localStorage.getItem("releaseDesignMessage")){
                	let message=JSON.parse(localStorage.getItem("releaseDesignMessage"))
                	this.title=message.title
                	this.style=message.style
                	this.otherStyle=message.otherStyle
                	this.layout=message.layout
                	this.otherLayout=message.otherLayout
                	this.place=message.place
					this.imgSrc=message.imgSrc
                	this.otherPlace=message.otherPlace 
                	this.area=message.area?message.area:""
					this.styleState=message.styleState
					this.layoutState=message.layoutState
					this.placeState=message.placeState
					try{
						if(message.html){
							this.editorCtxt.setContents({
								delta:message.html
							})
							this.editorCtxt.getContents({
								success:res=>{
									message.html=res.delta
									let text=res.text
									text = text.replace(/\r\n/g,"")
									text = text.replace(/\n/g,"");
									try{
										this.editorNumber=text.length
									}catch(e){
										this.editorNumber=0
									}
								}
							})
						}
					}catch(e){
						//TODO handle the exception
					}
                }
			},
			saveMessage(){
				let message={}
				message.title=this.title
				message.style=this.style
				message.otherStyle=this.otherStyle
				message.layout=this.layout
				message.otherLayout=this.otherLayout
				message.place=this.place
				message.otherPlace=this.otherPlace 
				message.area=this.area
				message.imgSrc=this.imgSrc
				message.styleState=this.styleState
				message.layoutState=this.layoutState
				message.placeState=this.placeState
				this.editorCtxt.getContents({
					success:res=>{
						message.html=res.delta
						message.html1=res.text.replace(/\r\n/g,"<br>").replace(/\n/g,"<br>").replace(/(<br\s?\/?>)+/gi,'$1')
						localStorage.setItem("releaseDesignMessage",JSON.stringify(message))
					}
				})
			},
			toAddImg(){
				uni.chooseImage({
					count:1,
					sizeType: ['compressed', 'original'],
					sourceType: ['album', 'camera'],
				    success: (res) => {
				        // 设置url的值，显示控件
				        this.url = res.tempFilePaths[0];
				    }
				})
			},
			confirm(e) {
				uni.showLoading({
				    title: '上传中...',
				})
				this.url = ''
				uni.uploadFile({
				    url: 'http://classic.wljiam.com/caapi/card/insertreminder',
				    filePath: e.detail.tempFilePath,
				    name: 'file',
				    formData: {
				        'userId': localStorage.getItem("userId")
				    },
				   success: (uploadFileRes) => {
						uni.hideLoading()
						this.imgSrc =JSON.parse(uploadFileRes.data).data
						this.checkCan()		
				    }
				})
			},
			cancel() {
				this.url = ''
			},
			toLookExample(){
				this.saveMessage()
				setTimeout(()=>{
					uni.navigateTo({
						url: '/pages/releaseDesign/designExample'
					})
				},20)
			},
			onEditorReady() {
			    uni.createSelectorQuery().select('#editor').context((res) => {
			        this.editorCtxt = res.context
					let message=localStorage.getItem("releaseDesignMessage")?JSON.parse(localStorage.getItem("releaseDesignMessage")):{}
					if(message.html){
						this.editorCtxt.setContents({
							delta:message.html
						})
						this.editorCtxt.getContents({
							success:res=>{
								message.html=res.delta
								let text=res.text
								text = text.replace(/\r\n/g,"")
								text = text.replace(/\n/g,"");
								try{
									this.editorNumber=text.length
								}catch(e){
									this.editorNumber=0
								}
							}
						})
					}
			    }).exec()
			},
			editorInput(e){
				if(e.timeStamp==0){
					let text=e.detail.text
					text = text.replace(/\r\n/g,"")
					text = text.replace(/\n/g,"");
					try{
						this.editorNumber=text.length
					}catch(e){
						this.editorNumber=0
					}
				}
			},
			addImgToEditor(){
				uni.chooseImage({
					count:1,
					sizeType: ['compressed', 'original'],
					sourceType: ['album', 'camera'],
				    success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						uni.showLoading({
						    title: '上传中...',
						})
						uni.uploadFile({
						    url: 'http://classic.wljiam.com/caapi/card/insertreminder',
						    filePath: tempFilePaths[0],
						    name: 'file',
						    formData: {
						        'userId': localStorage.getItem("userId")
						    },
						   success: (uploadFileRes) => {
								uni.hideLoading()
								this.editorCtxt.insertImage({
									src:JSON.parse(uploadFileRes.data).data,
								})		
						    }
						})
						
				    }
				})
			},
			checkCan(){
				let canDo=true
				if(this.style=='其它'&&!this.otherStyle){
					canDo=false
				}
				if(this.layout=='其它'&&!this.otherLayout){
					canDo=false
				}
				if(this.place=='其它'&&!this.otherPlace){
					canDo=false
				}
				if(this.imgSrc.indexOf('/static/img/tianjia.')!=-1){
					canDo=false
				}
				if(this.editorNumber<50){
					canDo=false
				}
				if(!this.area){
					canDo=false
				}
				this.canDo=canDo
			},
			toLook(){
				if(!this.canDo){
					return
				}
				this.saveMessage()
				setTimeout(()=>{
					if(this.isSuccess){
						uni.navigateTo({
							url: '/pages/releaseDesign/designLook?isEdit=true&isSuccess=true&examine='+this.examine+'&id='+this.id
						})
					}else if(this.isEdit){
						uni.navigateTo({
							url: '/pages/releaseDesign/designLook?isEdit=true&examine='+this.examine+'&id='+this.id
						})
					}else{
						uni.navigateTo({
							url: '/pages/releaseDesign/designLook?examine='+this.examine
						})
					}
				},20)
			},
			 toAdd(){
				if(!this.canDo){
					return
				}	
				uni.showLoading({
					mask: true
				})
				this.saveMessage()
				setTimeout(async ()=>{
					let message=JSON.parse(localStorage.getItem("releaseDesignMessage"))
					let data={}
					data.designTitle=message.title
					data.userId=localStorage.getItem("userId")
					data.coverImage=message.imgSrc
					data.designStyle=message.style=='其它'?12:message.styleState
					data.designApartment=message.layout=='其它'?12:message.layoutState
					data.designPlace=message.place=='其它'?12:message.placeState
					data.styleContent=message.style=='其它'?message.otherStyle:""
					data.apartmentContent=message.layout=='其它'?message.otherLayout:""
					data.placeContent=message.place=='其它'?message.otherPlace:""
					data.areaNumber=message.area
					data.designContent=JSON.stringify(message.html) 
					data.introduce=message.html1
					data.draft=1
					data.examine=this.examine
					let res
					if(this.isEdit&&!this.isSuccess){
						data.productId=""
						data.designId=this.id
						res=await urls.updaterotationChart(data)
					}else if(this.isEdit&&this.isSuccess){
						data.designId=this.id
						res=await urls.addArticleEdit(data)
					}else{
						res=await urls.addArticle(data)
					}
					uni.hideLoading()
					if(res.code==0){
						localStorage.removeItem("releaseDesignMessage")
						uni.navigateTo({
							url: '/pages/releaseDesign/underReview'
						})
					}
				},20)
			}
		},
	}
</script>

<style lang="scss">
.message{
	display: flex;
	padding: 0 30rpx;
	align-items: center;
	margin-top: 40rpx;
	font-size: 30rpx;
	input{
		height: 56rpx;
		width: 280rpx;
		border-radius: 2rpx;
		border: 1rpx solid #EEEEEE;
		color: #333333;
		letter-spacing: 1rpx;
		font-size: 30rpx;
		padding: 0 20rpx;
	}
	.message_key{
		font-size: 30rpx;
		width: 4.31em;
		text-align: right;
		color: #999999;
		letter-spacing: 1rpx;
	}
	view{
		margin-left: 20rpx;
		height: 56rpx;
		width: 220rpx;
		position: relative;
		border: 1rpx solid #EEEEEE;
		border-radius: 2rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		margin-right: 20rpx;
		text{
			font-size: 30rpx;
			color: #333333;
			letter-spacing: 1rpx;
		}
		image{
			position: absolute;
			height: 26rpx;
			width: 26rpx;
			right: 2rpx;
		}
	}
	.example{
		display: block;
		height: 48rpx;
		width: 142rpx;
		background-color: #C84739;
		border-radius: 6rpx;
		font-size: 28rpx;
		letter-spacing: 1rpx;
		color: #FFFFFF;
		line-height: 48rpx;
		text-align: center;
		margin-left: 20rpx;
	}
}
.title{
	margin-top: 60rpx;
	input{
		height: 85rpx;
		width: 690rpx;
		font-weight: bold;
		padding: 0 30rpx;
	}
}
.addImg{
	align-items: flex-start;
	image{
		height: 144rpx;
		width: 310rpx;
		margin-left: 20rpx;
		border-radius: 6rpx;
		background-color: #F4F4F4;
	}
}
.addImgToEditor{
	height: 84rpx;
	width:  690rpx;
	border: 1rpx solid #DDDDDD; 
	border-bottom: 0;
	margin-top: 30rpx;
	margin-left:30rpx;
	display: flex;
	align-items: center;
	padding-left: 43rpx;
	image{
		height: 58rpx;
		width: 58rpx;
	}
}
.editor_div{
	position: relative;
	text{
		position: absolute;
		font-size: 26rpx;
		color: #999999;
		letter-spacing: 1rpx;
		right: 56rpx;
		bottom: 19rpx;
	}
}
#editor{
	width: 690rpx;
	margin-left: 30rpx;
	border: 1rpx solid #DDDDDD;
	height: unset;
	min-height:  425rpx;
	max-height: 956rpx;
	overflow-y: auto;
}
.button{
	height: 98rpx;
	background-color: #FFFFFF;
	border-top: 1rpx solid #C84739;
	display: flex;
	position: fixed;
	width: 750rpx;
	bottom: 0;
	left: 0;
	view{
		height: 100%;
		width: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		text{
			color: #FFFFFF;
			font-size:34rpx ;
			letter-spacing: 1rpx;
			display: inline-block;
		}
	}
}
.popup_body{
	position: absolute;
	bottom: 43rpx;
	left:25rpx;
	width: 700rpx;
	background-color: #FFFFFF;
	border-radius: 25rpx;
	height: unset!important;
	view{
		width: 100%!important;
		height: 108rpx;
		border-bottom: 1rpx solid #D8D8D8;
		font-size: 34rpx;
		color: #A66354;
		line-height:107rpx ;
		text-align: center;
	}
	.popup_body_body{
		max-height: 377rpx;
		overflow-y: auto;
		height: unset;
	}
	.cancel{
		color: #999999;
	}
}
.popup_body>view:last-of-type{
	border: 0;
}
.popup_body_body>view:last-of-type{
	border: 0;
}
</style>
